import 'dart:async';

import 'package:common/base/base_gv_state.dart';
import 'package:common/base/base_lv_adapter.dart';
import 'package:common/base/base_stateful_widget.dart';
import 'package:common/base/channel/base_message_channel.dart';
import 'package:common/base/channel/base_method_channel.dart';
import 'package:common/constant/constant.dart';
import 'package:common/constant/date_format_constant.dart';
import 'package:common/constant/method_name_constant.dart';
import 'package:common/constant/route_args_config.dart';
import 'package:common/constant/route_name_config.dart';
import 'package:common/mvp/present/common_api_path.dart';
import 'package:common/mvp/present/download_present.dart';
import 'package:common/mvp/present/upload_present.dart';
import 'package:common/utils/date_time_util.dart';
import 'package:common/utils/log_util.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:toast/toast.dart';
import 'package:webview_flutter/webview_flutter.dart';
import '../model/grid_list_bean.dart';
import '../present/home_present.dart';

/// 网格列表
class GvListPage extends BaseStatefulWidget {
  const GvListPage({super.key});

  @override
  State<GvListPage> createState() => _GvListPageState();
}

class _GvListPageState extends BaseGvState<GvListPage, String> {
  late HomePresent _homePresent;
  late UploadPresent _uploadPresent;
  late DownLoadPresent _downloadPresent;
  final ImagePicker _picker = ImagePicker();

  @override
  void onStateInit() {
    super.onStateInit();
    _homePresent = HomePresent(this);
    _uploadPresent = UploadPresent(this);
    _downloadPresent = DownLoadPresent(this);
  }

  @override
  bool onNeedAppBar() {
    return false;
  }

  //创建GridView的Item,并且绑定数据
  @override
  BaseLvAdapter<String> onInitAdapter() {
    return BaseLvAdapter<String>((String t, int index) {
      return Container(
        height: 80,
        margin: const EdgeInsets.fromLTRB(5, 10, 5, 0),
        decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(5)),
        child: InkWell(
            onTap: () {
              switch(index){
                case 0:
                  _picker.pickMedia().then((xFile) {
                    if (null != xFile){
                      RxDouble progressValueObs = 0.0.obs;
                      showProgressDialog(context, progressValueObs);
                      _uploadPresent.uploadFileByPath(xFile.path,(int count, int total){
                        progressValueObs.value = count/total;
                      });
                    }
                  });
                  break;
                case 1:
                  _picker.pickMultipleMedia().then((xFiles) {
                    if (xFiles.isNotEmpty){
                      List<String> paths = xFiles.map((xFile) => xFile.path).toList();
                      RxDouble progressValueObs = 0.0.obs;
                      showProgressDialog(context, progressValueObs);
                      _uploadPresent.uploadFilesByPath(paths,(int count, int total){
                        progressValueObs.value = count/total;
                      });
                    }
                  });
                  break;
                case 2:
                  RxDouble progressValueObs = 0.0.obs;
                  showProgressDialog(context, progressValueObs);
                  _downloadPresent.downloadFileByPath('50090', '/sdcard/Download/${DateTimeUtil.formatCurrentDateTime(dateTimeFormat1)}.pkg', (count, total) {
                    progressValueObs.value = count/total;
                  });
                  break;
                case 3:
                  BaseMethodChannel channel = BaseMethodChannel();
                  channel.setMethodCallHandler((call) {
                    Navigator.of(context).pushNamed(RouteNameConfig.kAwakeByNativePage);
                    return Future(() => null);

                  });
                  Future<dynamic> result = channel.invokeMethod<String>(MethodNameConstant.methodNameNativeWebView,'{"${Constant.urlKey}":"file:///android_asset/JsTest.html","${Constant.toolbarKey}":true}');
                  result.then((value) {
                    LogUtil.stdPrint(value);
                  });
                break;
                case 4:
                  BaseMessageChannel channel = BaseMessageChannel();
                  Future<dynamic> result = channel.send('{"msg":"android receive flutter send msg"}');
                  result.then((value) {
                    LogUtil.stdPrint(value);
                  });
                break;
                case 5:
                  BaseMethodChannel channel = BaseMethodChannel();
                  Future<dynamic> result = channel.invokeMethod<String>(MethodNameConstant.methodNameNativeFunctionTest,'{}');
                  result.then((value) {
                    LogUtil.stdPrint(value);
                  });
                  break;
                case 6:
                  Map<String,String> args = {RouteArgsConfig.kUrl :'https://flutter.dev'};
                  Navigator.of(context).pushNamed(RouteNameConfig.kWebViewPage,arguments: args);
                  break;
                case 7:
                  Navigator.of(context).pushNamed(RouteNameConfig.kPathProviderPage);
                  break;
              }
            },
            child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
              (index % 2 == 1)
                  ? const Icon(Icons.access_alarm, color: Colors.red)
                  : const Icon(Icons.ac_unit, color: Colors.blue,
                    ),
              Text(
                t,
                textAlign: TextAlign.center,
                style: const TextStyle(fontSize: 12),
              )
            ])),
      );
    });
  }

  @override
  double onItemMaxWidth() {
    return 150;
  }

  @override
  void onLoadData() {
    showDelayLoadingDialog(context);
    Future.delayed(const Duration(seconds: 3), () {
      _homePresent.getGridList();
    });
  }

  @override
  Future<void> onPullRefresh() async {
    super.onPullRefresh();
    await Future.delayed(const Duration(seconds: 3), () {});
  }

  @override
  Future<void> onPullLoadMore() async {
    super.onPullLoadMore();
    await Future.delayed(const Duration(seconds: 3), () {});
  }

  @override
  void onSuccess<D>(D d , String apiPath) {
    super.onSuccess(d, apiPath);
    if ((HomePresent.kGetGridList == apiPath) && (d is GridListBean)) {
      GridListBean bean = d;
      refreshOrLoadSuccess(bean.title);
    } else if ((CommonApiPath.uploadFilePath == apiPath)
        || (CommonApiPath.uploadFilesPath == apiPath)){
      Toast.show("文件上传成功 fileId=$d",duration: Toast.lengthLong,gravity: Toast.bottom);
    }else{
      Toast.show("文件下载成功",duration: Toast.lengthLong,gravity: Toast.bottom);
    }
  }
}
